package com.mdp.im.core.publish;

import com.mdp.im.core.vo.SimpleUser;
import com.mdp.im.core.utils.MQChannelNames;
import com.mdp.im.core.utils.TopicTools;
import com.mdp.im.core.publish.api.Publisher;
import com.mdp.im.core.service.ImLoginUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 队列发布者实现类
 * 
 * @author chenyc
 * 
 * @date 2020/3/30
 */
@Service
public class MessagePublisher implements Publisher {

	Logger log = LoggerFactory.getLogger(MessagePublisher.class);

	@Autowired
	StringRedisTemplate redisTemplate;

	/**
	 * 为了避免私聊消息发往全部服务器，可以根据目标用户查找出目标用户所在的ip地址，根据地址进行分发
	 * @param toUserid
	 * @param message
	 */
	public void convertAndSendImPrichatMessage(String toUserid,String message) {
		SimpleUser user= ImLoginUtils.getSimpleUser(toUserid);
		if(user==null){
			return;
		}else{
			Map<String,Object> channelIds=user.getChannelIds();
			if(channelIds!=null && channelIds.size()>0){
				Iterator iter = channelIds.entrySet().iterator();
				Set<String> hostAddressSet=new HashSet<>();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					String hostAddress = (String) entry.getValue();
					if(!hostAddressSet.contains(hostAddress)){
						hostAddressSet.add(hostAddress);
						String topicName=TopicTools.getPrichatTopicName(hostAddress);
						log.debug("推送消息到消息中间件》》》》,订阅的主题名为："+topicName);
						redisTemplate.convertAndSend(topicName, message);
					}
				}


			}
		}

		
	}
	
	public void convertAndSendImGroupMessage(String groupId,String message) {
		redisTemplate.convertAndSend(TopicTools.getGroupTopicName(groupId),message);
	}

	public void convertAndSendImSysMessage(String message) {
		redisTemplate.convertAndSend(MQChannelNames.IM_SYS, message);
	}

    @Override
    public void publishPrichatMessage(String toUserid,String message) {
    	convertAndSendImPrichatMessage(toUserid,message); 
    }


	@Override
	public void publishGroupMessage(String groupId, String message) {
		convertAndSendImGroupMessage(groupId, message);
		
		//messageQueueService.pushGroupMessage(groupId, message); 
		//subscribers.startGroupMessageSubscriber(groupId);
		
	}



	@Override
	public void publishSysMessage(String message) {
		convertAndSendImSysMessage(message);
		//this.publishSysMessageToDbQueue(message);
		
	}


}
